package com.sakura.eduservice.controller.front;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakura.commonutils.JwtUtils;
import com.sakura.commonutils.R;
import com.sakura.eduservice.client.MemberClient;
import com.sakura.eduservice.entity.EduComment;
import com.sakura.eduservice.service.EduCommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@Api(tags = "CommentFrontController",description = "前台课程评论列表的显示")
@Slf4j
@RestController
@RequestMapping("/eduservice/commentfront")
public class CommentFrontController {
    @Autowired
    private EduCommentService commentService;

    @Autowired
    private MemberClient memberClient;


    @ApiOperation("发表评论")
    @PostMapping("publish/{token}")
    public R publishComment(@RequestBody EduComment comment, @PathVariable String token){
        //从request中获取header中的token值并提取其中的用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(token);
        if ("".equals(memberId)){
            //说明当前为无登录状态
            return R.error().message("该账号未登录,无法发表评论");
        }

        //根据会员id获取会员信息
        R r = memberClient.userInfo(memberId);
        if (!r.getSuccess()){
            return r;
        }
        for (Map.Entry<String,Object> entry:r.getData().entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
        LinkedHashMap<String,String> map = (LinkedHashMap<String, String>) r.getData().get("member");
        //添加上会员的相关信息
        comment.setMemberId(memberId).setAvatar(map.get("avatar")).setNickname(map.get("nickname"));
        //调用方法进行添加
        boolean result = commentService.save(comment);
        return result?R.ok():R.error();
    }


    @ApiOperation("分页显示评论列表")
    @PostMapping("list/{page}/{limit}")
    public R getCommentList(@PathVariable Long page,@PathVariable Long limit){

        IPage<EduComment> list = commentService.page(new Page<EduComment>(page, limit), null);

        return R.ok().data("list",list);
    }
}
